#!/bin/sh
# Distributed under the terms of the GNU General Public License v2
# v 0.0.1 2009/05/06 wenkangwei <wenkangwei@skytone.net.cn>

NETWORK_CONFIG=/etc/network/network.conf
NETWORK_STATUS=/tmp/network.stauts

up_lan(){
	ifconfig $1 up
#	/bin/net-connect $1
}

down_lan(){
	/bin/net-disconnect $1
	#ifconfig $1 down
}

up_wifi(){
	echo 1 > /proc/iwifi
	sleep 1
	ifconfig $1 up	
}

down_wifi(){
	/bin/net-disconnect $1
	#ifconfig $1 down
	echo 0 > /proc/iwifi	
	sleep 1
}

start() {
	#echo "start network."
	INTERFACE=`cat $NETWORK_CONFIG`
    case "$INTERFACE" in
		"eth0")
			echo "Up $INTERFACE."
			up_lan "$INTERFACE" && echo "$INTERFACE" > "/tmp/network.start"
			;;   
		""|"NONE"|"none")
			echo "Do not up network. or edit $NETWORK_CONFIG then retry..."
			;;                 
		*)
			echo "Up $INTERFACE."
			up_wifi "$INTERFACE" && echo "$INTERFACE" > "/tmp/network.start"
			;;
    esac 
}

stop() {
    echo "stop network."
	touch /tmp/network.start
	INTERFACE=`cat /tmp/network.start`
    case "$INTERFACE" in
		"eth0")
			echo "Down $INTERFACE."
			down_lan "$INTERFACE" && echo "$INTERFACE" > "/tmp/network.start"
			;;   
		""|"NONE"|"none")
			echo "No need to down network."
			;;                 
		*)
			echo "Down $INTERFACE."
			down_wifi "$INTERFACE" && echo "$INTERFACE" > "/tmp/network.start"
			;;
    esac 
	rm /tmp/network.start
}

restart() {
	stop
#	sleep 2
	start
	connect
}

connect() {
    echo "connect network."
	INTERFACE=`cat $NETWORK_CONFIG`
    case "$INTERFACE" in
		"eth0")
			echo "Connect $INTERFACE."
			echo "$INTERFACE" > "/tmp/network.start"
			/bin/net-connect $INTERFACE
			;;
		""|"NONE"|"none")
			echo "Do not connect any network..."
			;;
		*)
			echo "Connect $INTERFACE."
			echo "$INTERFACE" > "/tmp/network.start"
			/bin/wifi-reconnect $INTERFACE &
			;;
    esac 
}

write_status() {
	INTERFACE=`cat $NETWORK_CONFIG`
	case "$INTERFACE" in
		"eth0")
			echo "$INTERFACE $1" > $NETWORK_STATUS
			;;   
		""|"NONE"|"none")
			echo "network down" > $NETWORK_STATUS
			;;                 
		*)
			echo "$INTERFACE $1" > $NETWORK_STATUS
			;;
	esac 
}

status() {
	STATUS=`cat $NETWORK_STATUS`
	echo "$STATUS..."
}

case "$1" in
start)
	start
	write_status $1
	;;
stop)
	stop
	write_status $1
	;;
restart)
	restart
	write_status $1
	;;
connect)
	connect
	write_status $1
	;;
status)
	status
	;;
esac

exit 0



